package org.happycomp.radio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

/**
 * Playlist pro jednu stanici
 * @author pavels
 */
public class Playlist {
	
	public static final java.util.logging.Logger LOGGER = java.util.logging.Logger
			.getLogger(Playlist.class.getName());
	
	
	private Station station;
	
	private String version;
	private String numberofentries;
	private List<PlaylistEntry> playList = new ArrayList<PlaylistEntry>();

	public Playlist(Station station) {
		super();
		this.station = station;
	}

	/**
	 * Prida novou polozku PlaylistEntry
	 * @see PlaylistEntry
	 * @param entry play list entry
	 */
	public void addPlaylistEntry(PlaylistEntry entry) {
		this.playList.add(entry);
	}
	
	/**
	 * Odebere polozku PlaylistEntry
	 * @see PlaylistEntry
	 * @param entry playlist entry
	 */
	public void removePlaylistEntry(PlaylistEntry entry) {
		this.playList.remove(entry);
	}
	
	public List<PlaylistEntry> getEntries() {
		return new ArrayList<PlaylistEntry>(this.playList);
	}
	
	
	/**
	 * Stanice
	 * @return
	 */
	public Station getStation() {
		return station;
	}

	private PlaylistEntry factoryMethod(int where) {
		if (this.playList.size() < where)  {
			for (int i = this.playList.size(); i <where; i++) {
				this.playList.add(new PlaylistEntry(this.station));
			}
		}
		return this.playList.get(where - 1);
	}

	
	/**
	 * Verze
	 * @return
	 */
	public String getVersion() {
		return version;
	}

	/**
	 * Pocet polozek 
	 * @return
	 */
	public String getNumberofentries() {
		return numberofentries;
	}
	
	public void loadFromStream(String str) throws IOException {
		BufferedReader reader = new BufferedReader(new StringReader(str));
		String line = null;
		while((line = reader.readLine()) != null) {
			if ((line.trim().startsWith("[")) && 
				(line.trim().endsWith("]"))) {
				System.out.println("-prolog "+line);
			} else {
				System.out.println(line);
				int eqindex = line.indexOf('=');
				String leftSubString = line.substring(0,eqindex);
				String rightSubString = line.substring(eqindex+1);
				char charAt = leftSubString.charAt(leftSubString.length()-1);
				if (Character.isDigit(charAt)) {
					int digit = Character.digit(charAt, 10);
					PlaylistEntry entry = factoryMethod(digit);
					entry.init(leftSubString, rightSubString);
				} else {
					if (leftSubString.toLowerCase().startsWith("version")) {
						this.version = leftSubString;
					} else if (leftSubString.toLowerCase().startsWith("numberofentries")) {
						this.numberofentries = leftSubString;
					} else {
						LOGGER.info("ommiting '"+leftSubString+"'");
					}
				}
			}
		}
	}
}  
